package com.zb.utils;

import com.zb.exception.ZbException;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 替换工具类
 * @Author WEN
 * @Date 2023/9/15 0015
 **/
public class TemplateReplaceUtil {
    private static String REGEX = "(\\$\\{)([\\w]+)(\\})|(\\{)([\\w]+)(\\})";

    public static String template(String templateStr, Map<String, String> paramMap) throws ZbException {
        if (StringUtils.isBlank(templateStr)) {
            throw new ZbException("模板不符合规范！");
        }
        if (null == paramMap || paramMap.isEmpty()) {
            throw new ZbException("模板参数不符合规范！");
        }
        Matcher matcher = Pattern.compile(REGEX).matcher(templateStr);
        StringBuffer buffer = new StringBuffer();
        String templateFieldName = null;
        while (matcher.find()) {
            templateFieldName = matcher.group().replace("$", "").replace("{", "").replace("}", "");
            if (null == paramMap.get(templateFieldName)) {
                throw new ZbException("缺少模板字段：" + templateFieldName );
            }
            matcher.appendReplacement(buffer, (String) paramMap.get(templateFieldName));
        }
        matcher.appendTail(buffer);
        return buffer.toString();
    }




//    public static void main(String[] args) throws ZbException {
//        String s="尊敬的${name}, 您的订单为:${order} 支付金额为:${pay} 请尽快支付{dd}";
//        System.out.println("替换前："+s);
//        Map<String,Object> params = new HashMap<>();
//        params.put("name","Frank");
//        params.put("order","123456789");
//        params.put("pay","123");
//        params.put("dd","123");
//        String template = template(s, params);
//        System.out.println(template);
//    }

}
